using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace RadaCode.SwissKnife.Random
{
    public class RandomWordSearcher
    {
        private readonly int _minWordLength;

        private class RssEntry
        {
            public string Link { get; set; }
            public string Title { get; set; }
            public string Description { get; set; }
        }

        private MersenneTwister randomer;

        private string _rssUrl = string.Empty;

        public RandomWordSearcher(string rssUrl, int minWordLength)
        {
            randomer = new MersenneTwister();
            _rssUrl = rssUrl;
            _minWordLength = minWordLength;
        }

        public RandomWordSearcher(string rssUrl):this(rssUrl, 3)
        {}

        public RandomWordSearcher(int minWordLength): this("http://news.google.com/news?ned=us&topic=h&output=rss", minWordLength)
        {}

        public RandomWordSearcher() : this("http://news.google.com/news?ned=us&topic=h&output=rss", 3)
        {}

        private IEnumerable<RssEntry> GetRssFeed()
        {
            XDocument feedXml;

            feedXml = XDocument.Load(_rssUrl);

            var feeds = from feed in feedXml.Descendants("item")
                        select new RssEntry
                        {
                            Title = feed.Element("title").Value,
                            Link = feed.Element("link").Value,
                            Description = RadaCode.SwissKnife.HtmlRemoval.RemoveHTML(feed.Element("description").Value)
                        };
            return feeds;
        }

        public string GetRandomWord()
        {
            var res = string.Empty;

            var rssFeeds = GetRssFeed();

            var words = rssFeeds.ToArray()[randomer.Next(0, rssFeeds.Count() - 1)].Description.Split(' ');
            
            while (res.Length < _minWordLength)
            {
                res = words[randomer.Next(0, words.Length - 1)];
            }

            return res;
        }

        public string[] GetRandomWords(int count)
        {
            var res = new string[count];

            var rssFeeds = GetRssFeed();

            for (var i = 0; i < count; i++)
            {
                var words = rssFeeds.ToArray()[randomer.Next(0, rssFeeds.Count() - 1)].Description.Split(' ');

                do
                {
                    res[i] = words[randomer.Next(0, words.Length - 1)];
                } while (res[i].Length < _minWordLength);
            }

            return res;
        }
    }
}